package logic

import (
	"bluebell/dao/mysql"
	"bluebell/models"
	"bluebell/pkg/jwt"
	"bluebell/pkg/snowflake"
	"errors"
)

// SignUp 注册业务逻辑
func SignUp(p *models.RegisterForm) (error error){
	// 1、判断用户不存在
	err := mysql.CheckUserExist(p.UserName)
	if err.Error() != mysql.ErrorUserNotExit{
		return err
	}
	// 2、生成UID
	userId, err := snowflake.GetID()
	if err != nil {
		return errors.New(mysql.ErrorGenIDFailed)
	}
	// 构造一个User实例
	u := models.User{
		UserId:   userId,
		UserName: p.UserName,
		Password: p.Password,
		Email:    p.Email,
		Gender:   p.Gender,
	}
	// 3、保存进数据库
	return mysql.InsertUser(u)
}

// Login 登录业务逻辑代码
func Login(p *models.LoginForm)(user *models.User,error error){
	user = &models.User{
		UserName: p.UserName,
		Password: p.Password,
	}
	if err := mysql.Login(user); err != nil {
		return nil, err
	}
	//生成JWT
	accessToken,refreshToken,err := jwt.GenToken(user.UserId,user.UserName)
	if err != nil{
		return nil,err
	}
	user.AccessToken = accessToken
	user.RefreshToken = refreshToken
	return user,nil
}